package com.guo.loadinganim;

import android.animation.Animator;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 适用于卡片形态变换的管理工具类
 */
public class LayoutAnimManager {
    private static final String TAG = "LayoutAnimManager";
    private List<ViewParams> animViewList = new ArrayList<>();
    private final String BIG_PRE = "_b";
    private final String SMALL_PRE = "_s";
    private List<Integer> mGoneViews = new ArrayList<>();
    private final int ANIM_TIMER = 200;

    //执行初始化
    public void initialize(ViewGroup viewGroup){
        Log.d(TAG, "begin init");
        prepareView(viewGroup);
        viewGroup.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                viewGroup.getViewTreeObserver().removeOnPreDrawListener(this);
                parseParams(viewGroup);
                restoreGoneView(viewGroup);
                Log.d(TAG, "finish init");
                return false;
            }
        });
    }

    public void changeView(boolean toBigView, ViewGroup viewGroup){
        for(ViewParams p : animViewList){
            performViewLayoutAnim(p, viewGroup, toBigView);
        }
    }


    /**
     * 将视图准备至子视图可测量状态(找出设定为View.GONE子视图，调整为INVISIBLE，结束后恢复)
     */
    private void prepareView(ViewGroup viewGroup){
        //被隐藏的子视图
        mGoneViews.clear();
        findGoneView(viewGroup);
    }

    private void findGoneView(ViewGroup viewGroup){
        int childCount = viewGroup.getChildCount();
        for(int i = 0; i < childCount; i++){
            View child = viewGroup.getChildAt(i);
            if(child instanceof ViewGroup){
                findGoneView((ViewGroup) child);
            }else{
                if(child.getVisibility() == View.GONE){
                    mGoneViews.add(child.getId());
                    child.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

    private void restoreGoneView(ViewGroup viewGroup){
        for(int i = 0; i < mGoneViews.size(); i++){
            int id = mGoneViews.get(i);
            View v = viewGroup.findViewById(id);
            if(null != v){
                v.setVisibility(View.GONE);
            }
        }
    }


    private void parseParams(ViewGroup viewGroup){
        int childCount = viewGroup.getChildCount();
        for(int i = 0; i < childCount; i++){
            View child = viewGroup.getChildAt(i);
            if(child instanceof ViewGroup){
                parseParams((ViewGroup)child);
            }else{
                String tag = (String) child.getTag();
                if(null != tag){
                    if(tag.endsWith(BIG_PRE)){
                        String t = tag.replaceAll(BIG_PRE,"");
                        //插入视图列表
                        ViewParam param = new ViewParam();
                        param.id = child.getId();
                        param.x = (int)child.getX();
                        param.y = (int)child.getY();
                        param.width = child.getWidth();
                        param.height = child.getHeight();
                        if(child instanceof TextView){
                            TextView tv = (TextView)child;
                            Paint paint = new Paint();
                            paint.setTextSize(tv.getTextSize());
                            paint.setTypeface(tv.getTypeface());
                            int text_width = (int)paint.measureText(tv.getText().toString());
                            Rect bounds = new Rect();
                            paint.getTextBounds(tv.getText().toString(), 0, tv.getText().length(), bounds);
                            int text_height = bounds.height();
                            param.width = text_width;
                            param.height = text_height;
                        }
                        insertParam(t, param, BIG_PRE);

                    }else if(tag.endsWith(SMALL_PRE)){
                        String t = tag.replaceAll(SMALL_PRE,"");
                        //插入视图列表
                        ViewParam param = new ViewParam();
                        param.id = child.getId();
                        param.x = (int)child.getX();
                        param.y = (int)child.getY();
                        param.width = child.getWidth();
                        param.height = child.getHeight();
                        if(child instanceof TextView){
                            TextView tv = (TextView)child;
                            Paint paint = new Paint();
                            paint.setTextSize(tv.getTextSize());
                            paint.setTypeface(tv.getTypeface());
                            int text_width = (int)paint.measureText(tv.getText().toString());
                            Rect bounds = new Rect();
                            paint.getTextBounds(tv.getText().toString(), 0, tv.getText().length(), bounds);
                            int text_height = bounds.height();
                            param.width = text_width;
                            param.height = text_height;
                        }
                        insertParam(t, param, SMALL_PRE);
                    }
                }
            }
        }
    }

    private void insertParam(String tag, ViewParam param, String type){
        for(ViewParams p : animViewList){
            if(tag.equals(p.tagContent)){
                if(type.equals(BIG_PRE)){
                    p.b_View_P = param;
                }else{
                    p.s_View_P = param;
                }
                return;
            }
        }
        //无记录，插入数据
        ViewParams p = new ViewParams();
        p.tagContent = tag;
        if(type.equals(BIG_PRE)){
            p.b_View_P = param;
        }else{
            p.s_View_P = param;
        }
        animViewList.add(p);
    }

    //执行单个元素的切换动效
    private void performViewLayoutAnim(ViewParams params, ViewGroup viewGroup, boolean toBigView){
        ViewParam start , end;
        View target;
        if(toBigView){
            start = params.s_View_P;
            end = params.b_View_P;
        }else{
            start = params.b_View_P;
            end = params.s_View_P;
        }
        target = viewGroup.findViewById(end.id);
        float scaleX = end.width == 0 ? 1 : 1.00f * start.width / end.width;
        float scaleY = end.height == 0? 1 : 1.00f * start.height / end.height;
        target.setPivotY(0.5f);
        target.setPivotX(0.5f);
        target.setScaleX(scaleX);
        target.setScaleY(scaleY);
        target.setTranslationX(start.x - end.x);
        target.setTranslationY(start.y - end.y);

        viewGroup.findViewById(start.id).setVisibility(View.GONE);
        viewGroup.findViewById(end.id).setVisibility(View.VISIBLE);

        Log.d(TAG, "anim begin");
        target.animate().scaleX(1).scaleY(1).translationX(0).translationY(0).setDuration(ANIM_TIMER).setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                Log.d(TAG, "anim over");
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
    }


    private class ViewParams{
        String tagContent;
        //小时图下的位置参数
        ViewParam s_View_P;
        //大师图的位置参数
        ViewParam b_View_P;
    }

    private class ViewParam{
        //View的id
        int id;
        //View的x,y坐标，宽，高
        int x, y, width, height;
    }

}
